<script setup lang="tsx">
import { Button, Popconfirm } from 'ant-design-vue';
import EZUIKit from 'ezuikit-js';
import { onBeforeUnmount, ref } from 'vue';
import { useTable, useTableOperate, useTableScroll } from '@/hooks/common/table';
import { $t } from '@/locales';
import { getVideoMonitorListApi, getVideoUrlApi, videoMonitorDeleteApi } from '@/service/api/businessApi';
import { useProjectStore } from '@/store/modules/project';
import { useAuthStore } from '@/store/modules/auth';
import UserOperateDrawer from './modules/operate-drawer.vue';
const authStore = useAuthStore();
const projectStore = useProjectStore();

const { tableWrapperRef, scrollConfig } = useTableScroll();

const { columns, columnChecks, data, getData, loading, mobilePagination } = useTable({
    apiFn: getVideoMonitorListApi,
    apiParams: {
        pageNo: 1,
        pageSize: 10,
        projectId: projectStore.currentProject?.id
    },
    columns: (): any => [
        {
            key: 'sequence',
            dataIndex: 'sequence',
            title: '序号',
            width: 60
        },
        {
            key: 'name',
            dataIndex: 'name',
            title: '监控名称'
        },
        {
            title: '创建时间',
            dataIndex: 'gmtCreated',
            key: 'gmtCreated',
            width: 160
        },
        {
            title: '更新时间',
            dataIndex: 'gmtModified',
            key: 'gmtModified',
            width: 160
        },
        {
            key: 'operate',
            title: $t('common.operate'),
            align: 'center',
            width: 180,
            customRender: ({ record }: any) => (
                <div class="flex-center gap-8px">
                    <Button type="primary" ghost size="small" onClick={() => paly(record.serialNumber,record.channelNo)}>
                        播放
                    </Button>
                    {authStore.userInfo.userType !== 3 && (
                        <Button
                            type="primary"
                            ghost
                            size="small"
                            onClick={() => edit(record.id)}
                        >
                            编辑
                        </Button>
                    )}
                    {authStore.userInfo.userType !== 3 && (
                        <Popconfirm
                            title="确认删除吗？"
                            onConfirm={() => handleDelete(record.id)}
                        >
                            <Button danger size="small">
                                删除
                            </Button>
                        </Popconfirm>
                    )}
                </div>
            )
        }
    ]
});

const { drawerVisible, operateType, editingData, handleAdd, handleEdit, checkedRowKeys, onDeleted } = useTableOperate(
    data as any,
    getData
);

const visible = ref(false);
const playUrl = ref('');
function paly(url: string,channelNo: number) {
    if (!url) {
        window.$message?.error('未配置视频地址', 2);
        return;
    }
    visible.value = true;
    playUrl.value = url;
    setTimeout(() => {
        createVideo(url,channelNo);
    }, 100);
}

let myPlayer: any = null;
const createVideo = (serialNumber: any,channelNo: any) => {
    getVideoUrlApi({ serialNumber,channelNo }).then((res: any) => {
        const data = res.data;
        myPlayer = new EZUIKit.EZUIKitPlayer({
            id: 'my-video',
            accessToken: data.accessToken,
            url: data.url,
            audio: 0,
            autoplay: true,
            width: document.body.clientWidth - 40,
            height: document.body.clientHeight - 80
        });
    });
};

const playClose = () => {
    if (myPlayer === null) return;
    myPlayer.stop();
};

onBeforeUnmount(() => {
    playClose();
});

async function handleDelete(id: any) {
    const res = await videoMonitorDeleteApi(id);
    if (res.error === null) await onDeleted();
}

function edit(id: number) {
    handleEdit(id);
}
</script>

<template>
    <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
        <ACard
            title="监控列表"
            :bordered="false"
            :body-style="{ flex: 1, overflow: 'hidden' }"
            class="flex-col-stretch sm:flex-1-hidden card-wrapper"
        >
            <template #extra>
                <TableHeaderOperation
                    v-model:columns="columnChecks"
                    :disabled-delete="checkedRowKeys.length === 0"
                    :loading="loading"
                    @add="handleAdd"
                    @refresh="getData"
                />
            </template>
            <ATable
                ref="tableWrapperRef"
                :columns="columns"
                :data-source="data"
                size="small"
                :scroll="scrollConfig"
                :loading="loading"
                row-key="id"
                :pagination="mobilePagination"
                class="h-full"
                children-column-name="childDeviceInfo"
            />

            <UserOperateDrawer
                v-model:visible="drawerVisible"
                :operate-type="operateType"
                :row-data="editingData"
                @submitted="getData"
            />
        </ACard>

        <AModal
            v-model:open="visible"
            title="视频监控"
            width="100%"
            :footer="null"
            wrap-class-name="full-modal"
            :destroy-on-close="true"
            @cancel="playClose"
        >
            <div id="my-video" style="width: 100%; height: 100%; object-fit: fill"></div>
        </AModal>
    </div>
</template>

<style lang="scss">
.full-modal {
    .ant-modal {
        max-width: 100%;
        top: 0;
        padding-bottom: 0;
        margin: 0;
    }
    .ant-modal-content {
        display: flex;
        flex-direction: column;
        height: calc(100vh);
    }
    .ant-modal-body {
        flex: 1;
    }
}
</style>
